package com.thread.lianxi;

public class WaitAndNotify2 extends Thread {

	String name;
	Object prev;
	Object self;

	public WaitAndNotify2(String name, Object self, Object prev) {
		super(name);
		this.name = name;
		this.prev = prev;
		this.self = self;
	}

	public void run() {
		int count = 10;
		while (count > 0) {
			synchronized (prev) {
				synchronized (self) {
					System.out.print(name);
					count--;
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					self.notify();
				}
				try {
					prev.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

		// 如果确实下面这段代码，那么会有两个线程无法退出,因为输出A的线程打印10次后，没办法调用notify()通知打印B的线程，以此内存.
		synchronized (self) {
			self.notify();
		}

	}

	public static void main(String[] args) throws InterruptedException {

		Object a = new Object(), b = new Object(), c = new Object();
		(new WaitAndNotify2("A", a, c)).start();
		(new WaitAndNotify2("B", b, a)).start();
		(new WaitAndNotify2("C", c, b)).start();

	}
}
